package com.ricchieri.lazymodel;

import java.util.List;
import java.util.Map;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import com.ricchieri.common.BusinessSettings;
import com.ricchieri.filter.UserFilter;
import com.ricchieri.model.User;
import com.ricchieri.service.interf.IUserService;

public class UserLazyDataModel extends LazyDataModel<User> {

	private static final long serialVersionUID = 4593253494642335825L;

	private List<User> users;
	private IUserService userService;
	private UserFilter userFilter;
	
	public UserLazyDataModel(IUserService userService, UserFilter userFilter) {
		super();
		this.userFilter = userFilter;
		this.userService = userService;
	}
	
    @Override
    public Object getRowKey(User user) {
        return user.getId();
    }

    @Override
    public User getRowData(String userId) {
        int id = Integer.valueOf(userId);

        for (User user : users) {
            if(id == user.getId()) {
                return user;
            }
        }
        return null;
    }
    
	@Override
	public List<User> load(int startingAt, int maxPerPage, String sortField, 
			SortOrder sortOrder, Map<String, String> filters) {
		
		userFilter.setSortField(sortField);
		userFilter.setSortOrder(sortOrder.toString());
		
        if(getRowCount() <= 0) {
            setRowCount(getUserService().getAllUserCountByFilter(userFilter));
        }
        
        if(getRowCount() == startingAt && getRowCount()  != 0) {
        	startingAt = startingAt - BusinessSettings.ROW_MAX_RESULT;
        }
		users = getUserService().getAllUserPaginatedByFilter(userFilter, startingAt);

        setPageSize(BusinessSettings.ROW_MAX_RESULT);
        
        return users;
	}

	public List<User> getUsers() {
		return users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}

	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public UserFilter getUserFilter() {
		return userFilter;
	}

	public void setUserFilter(UserFilter userFilter) {
		this.userFilter = userFilter;
	}
}
